﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

namespace ceTerm
{
    public partial class RaftanIndirme : XForm
    {
        public enum ListType
        {
            RaftanIndirme = 1,  /*ve Çıkış*/
            TopArama
        }

        public RaftanIndirme(ListType tip)
        {
            InitializeComponent();

            panel2.Visible = btnSave.Visible = tip == ListType.RaftanIndirme;
            if (tip == ListType.TopArama)
                this.Text = "Top Arama";

            this.WindowState = FormWindowState.Maximized;
            this.KeyPreview = true;

            Terminal.SetActivatedForm(this);

            cl = Color.White;
            panelM.BackColor = cl;
            panelM.AutoScroll = true;

            this.tmrRefresher.Interval = 1000;
            this.tmrRefresher.Tick += new System.EventHandler(this.tmrRefresher_Tick);
            tmrRefresher.Enabled = true;

            //lblKalan.Click += new EventHandler(linkLabel1_Click);

            DataTable dt = Main.ceWS.GetCikisEmirleri(Main.Password);
            foreach (DataRow dr in dt.Rows)
                comboBox1.Items.Add(dr["val"].ToString());

            comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);

            btnDBden.Click += new EventHandler(btnDBden_Click);
            btnDuzenle.Click += new EventHandler(btnDuzenle_Click);
        }

        void btnDuzenle_Click(object sender, EventArgs e)
        {
            List<string> toplar = new List<string>();
            if (dtTop != null)
                foreach (DataRow top in dtTop.Rows)
                    toplar.Add(top["RollId"].ToString());

            using (AranacakToplar at = new AranacakToplar(string.Join(Environment.NewLine, toplar.ToArray())))
            {
                if (at.ShowDialog() == DialogResult.OK)
                {
                    if (dtTop != null)
                        dtTop.Rows.Clear();

                    ds = null;
                    try
                    {
                        string rolls = string.Empty;
                        foreach (int r in at.rolls)
                            rolls += r.ToString() + ";";

                        ds = Main.ceWS.GetTopByRollId(Main.Password,rolls.Substring(0, rolls.Length - 1));
                    }
                    catch (Exception ex)
                    {
                        ShowException(ex);
                        return;
                    }

                    Init();
                }
            }
        }

        void btnDBden_Click(object sender, EventArgs e)
        {
            try
            {
                if (dtTop != null)
                    dtTop.Rows.Clear();

                ds = Main.ceWS.GetTopByRollId(Main.Password,"*");
                
                Init();
            }
            catch (Exception ex)
            {
                ShowException(ex);
                return;
            }
        }

        DataSet ds;
        DataTable dtRaf, dtTop;
        Dictionary<int, int> liste = new Dictionary<int, int>();        // RollId, ShelfId
        void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string[] parts = comboBox1.SelectedItem.ToString().Split(".".ToCharArray());
            if (parts.Length > 1)
            {
                ds = null;
                try
                {
                    ds = Main.ceWS.GetTopByCikisEmri(Main.Password,intParse(parts[0]));
                }
                catch (Exception ex)
                {
                    ShowException(ex);
                    return;
                }

                ToCut = ds.Tables[2].Rows[0]["TOCUT"].ToString() != "0";

                Init();
            }
        }

        bool ToCut = false;

        private void Init()
        {
            dtRaf = ds.Tables[0];
            dtTop = ds.Tables[1];

            shelves.Clear();
            foreach (DataRow raf in dtRaf.Rows)
                shelves.Add(intParse(raf["ShelfId"]), (string)raf["Shelf"]);

            panelM.SuspendLayout();
            panelM.Controls.Clear();
            rolls.Clear();
            rollCnt = 0;
            rollX = CurrentShelfId = -1;
            foreach (DataRow top in dtTop.Rows)
                MakeLabel(intParse(top["ShelfId"]), intParse(top["RollId"]));
            panelM.ResumeLayout();

            //UpdateButtonStatus();
            UpdateCounts();

            Terminal.PlaySuccess();

            //Terminal.StartRFID();
            //lblStep.Text = "Önce topları sonra arabanın barkodunu okutun.";
            tmrRefresher.Enabled = true;
        }

        void linkLabel1_Click(object sender, EventArgs e)
        {
            //panel1.Visible = !panel1.Visible;
        }

        int rollCnt;
        Label[] lblArr = new Label[500];

        Dictionary<int, int> rolls = new Dictionary<int, int>();
        Dictionary<int, string> shelves = new Dictionary<int, string>();

        Color cl;
        Random rnd = new Random();
        delegate void UpdateHandler();
        void tmrRefresher_Tick(object sender, EventArgs e)
        {
            tmrRefresher.Enabled = false;
            this.Invoke(new UpdateHandler(Colorize));
            tmrRefresher.Enabled = true;
        }

        private void Colorize()
        {
            foreach (object lbl in panelM.Controls)
                if (lbl is Label)
                    if (((Label)lbl).Tag is DateTime)
                        if (((DateTime)((Label)lbl).Tag).AddSeconds(1.5) < DateTime.Now)
                            ((Label)lbl).BackColor = cl;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F18: // AT570, AT870 Gun Trigger 
                case Keys.F19: // AT570, AT870 Gun Trigger                     
                    Terminal.StartBarcode();
                    //power.Value = Settings.Power.OkumaMin;
                    //Terminal.RFID.SET_PowerControl((uint)power.Value);
                    break;

                default:
                    break;
            }
            base.OnKeyDown(e);
        }

        protected override void OnKeyUp(KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.F18: // AT570, AT870 Gun Trigger 
                case Keys.F19: // AT570, AT870 Gun Trigger 
                    Terminal.StopBarcode();
                    break;

                default:
                    break;
            }
            base.OnKeyUp(e);
        }

        public override void lDetay_Click(object sender, EventArgs e)
        {
            //    Browse("TopDetay.aspx?TopId=" + tvTop.SelectedNode.Text, true, "Top Detayı");
            //Browse("TopDetay.aspx?TopId=" + lDetay.Tag.ToString(), true, "Top Detayı");
        }

        private void RaftanIndirme_Closing(object sender, CancelEventArgs e)
        {
            if (btnSave.Visible)
                if (btnSave.Enabled)
                    if (Main.AskYesNo("Kaydetmediniz. Yine de çıkmak ister misiniz?", "Dikkat") == DialogResult.No)
                        e.Cancel = true;
        }

        int ShelfId = -1;

        public override void OnScaned(string BarcodeValue, string TypeName, string TypeID)
        {
            Terminal.StopBarcode();
            CleanBarcode(ref BarcodeValue, TypeName);

            int iBarcode = intParse(BarcodeValue);
            if (iBarcode < 1)
                return;

            if (BarkodTipi(iBarcode) == barkodTipleri.RafAraba)
            {
                iBarcode -= (int)1e9;
                DataRow dr = null;

                try
                {
                    dr = Main.ceWS.GetRafDetay(Main.Password,iBarcode).Rows[0];
                    //if ((string)dr["Tip"] == "R")
                    //    return;

                    //if ((string)dr["Tip"] == "Ç")
                    //    if (ToCut)
                    //    {
                    //        MessageBox.Show("Bölünecek top(lar) var. Bunları bölmeden çıkış yapamazsınız!");
                    //        return;
                    //    }


                    ShelfId = (int)dr["ShelfId"];
                }
                catch (Exception ex)
                {
                    ShowException("Veritabanı hatası!", "Hata", ex);
                    return;
                }

                Terminal.Scanner.Vibrator(true);
                Thread.Sleep(500);
                Terminal.PlaySuccess();
                Terminal.Scanner.Vibrator(false);
                return;
            }

            else if (rolls.ContainsKey(iBarcode))
            {
                if (ShelfId < 0)
                {
                    MessageBox.Show("Paletin veya çıkış kapısının barkodu, toplardan önce okutulmalı!");
                    return;
                }

                if (lblArr[rolls[iBarcode]].ForeColor != Color.LightGray)
                {
                    lblArr[rolls[iBarcode]].ForeColor = Color.LightGray;

                    //ekle

                    if (!liste.ContainsKey(iBarcode))
                        liste.Add(iBarcode, ShelfId);

                    btnSave.Enabled = true;

                    UpdateCounts();
                    Terminal.PlaySuccess();
                    return;
                }
                else
                {
                    lblArr[rolls[iBarcode]].ForeColor = Color.Black;
                    //çıkar
                    if (liste.ContainsKey(iBarcode))
                        liste.Remove(iBarcode);

                    UpdateCounts();
                    Terminal.Scanner.Vibrator(true);
                    Thread.Sleep(500);
                    //Terminal.PlaySuccess();
                    Terminal.Scanner.Vibrator(false);
                    return;

                }
            }

            ShowException("Listede olmayan bir top okuttunuz.", "Hata", null);

        }


        int rpc = 9; //RollsPerColumn
        int rollX = -1, rollY;
        int CurrentShelfId;
        void MakeLabel(int ShelfId, int RollId)
        {
            if (CurrentShelfId != ShelfId)
            {
                CurrentShelfId = ShelfId;
                rollX++;
                rollY = 0;
                MakeHeader(ShelfId);
            }

            rollY = (rollY + 1) % rpc;

            if (rollY == 0)
                rollX++;
                //rollY = 1;

            //TODO:Kontrol
            Label lbl = new Label();
            lbl.Bounds = new Rectangle(rollX * 47, rollY * 19, 42, 18);
            lbl.BackColor = cl;
            lbl.Text = RollId.ToString();// cnt.ToString().PadLeft(5, '0');
            lbl.ForeColor = Color.Black;
            lbl.TextAlign = ContentAlignment.TopRight;
            panelM.Controls.Add(lbl);

            //lbl.Click += new EventHandler(lbl_Click);

            lblArr[rollCnt] = lbl;
            if (!rolls.ContainsKey(RollId))
                rolls.Add(RollId, rollCnt);
            rollCnt++;
        }

        void lbl_Click(object sender, EventArgs e)
        {
            lDetay.Tag = ((Label)sender).Text;
        }

        void MakeHeader(int ShelfId)
        {
            Color c = Color.OrangeRed;
            Label lbl = new Label();
            lbl.Bounds = new Rectangle(rollX * 47, 0, 42, 18);
            lbl.BackColor = c;  // SystemColors.ControlDark;
            lbl.ForeColor = cl;
            lbl.Text = shelves[ShelfId];
            lbl.TextAlign = ContentAlignment.TopRight;
            panelM.Controls.Add(lbl);


            Panel p = new Panel();
            p.Size = new Size(1, 165);
            p.BackColor = c;
            //TODO: Kontrol
            p.Location = new Point(rollX * 47 - 3, 0);
            panelM.Controls.Add(p);

            //System.Drawing.Pen myPen = new System.Drawing.Pen(System.Drawing.Color.Gray);
            //System.Drawing.Graphics formGraphics = panel1.CreateGraphics();
            //formGraphics.DrawLine(myPen, rollX * 47 - 5, 0, rollX * 47 - 5, 200);
            //myPen.Dispose();
            //formGraphics.Dispose();
        }

        private void UpdateCounts()
        {
            int var = 0;
            for (int i = 0; i < rollCnt; i++)
                if (lblArr[i].BackColor == cl && lblArr[i].ForeColor == Color.Black)
                    var++;

            lblKalan.Text = "Kalan: " + var;
        }

        private bool IsArabaBarcode(int barcode)
        {
            if (BarkodTipi(barcode) == barkodTipleri.RafAraba)
            {
                barcode -= (int)1e9;
                DataTable dt = Main.ceWS.GetRafDetay(Main.Password,barcode);
                return (dt.Rows.Count > 0 && 
                    (string)dt.Rows[0]["Tip"] != "R");
            }
            else
                return false;
        }

        public override void GetAccessEPC(string EPC)
        {
            int EPCint;
            double dRSSI;
            resolveEPC(EPC, out EPCint, out dRSSI);

            if (rolls.ContainsKey(EPCint))
            {
                double doublePower = ((100 + dRSSI) - 35.9) * 9;
                int power = (int)Math.Floor(doublePower);
                if (power > 255) power = 255;
                if (power < 0) power = 0;

                lblArr[rolls[EPCint]].BackColor = Color.FromArgb(255 - power, 255, 255 - power);
                lblArr[rolls[EPCint]].Tag = DateTime.Now;    // güncelleniyor
            }
        }


        private void resolveEPC(string EPC, out int EPCi, out double RSSI)
        {
            if (EPC.Length > 20 && EPC[0] == '3')
                EPC = EPC.Remove(0, 1);

            if (EPC.Contains(","))
            {
                string[] temp = EPC.Split(",".ToCharArray());

                EPCi = intParse(temp[0]);
                RSSI = Double.Parse(temp[1].Replace("RSSI=", ""));
                //(int)((80+Double.Parse(temp[1].Replace("RSSI=", "")))*2);    //30-80 arası
            }
            else
            {
                EPCi = intParse(EPC);
                RSSI = 0;
            }
        }


        //private void btnSave_Click(object sender, EventArgs e)
        //{
        //    SetButtonsStatus(this, false);

        //    int var = 0;
        //    for (int i = 0; i < rollCnt; i++)
        //        if (lblArr[i].BackColor == cl && lblArr[i].ForeColor == Color.Black)
        //        {
        //            var++;
        //            break;
        //        }

        //    if (var > 0)
        //    {
        //        if (Main.AskYesNo("Tüm topları almadınız. Yine de kaydetmek ister misiniz?", "Eksik") == DialogResult.No)
        //            return;
        //    }

        //    DataTable dtCikilanToplar = new DataTable("cikilanToplar");
        //    dtCikilanToplar.Columns.Add("RollId", typeof(int));
        //    dtCikilanToplar.Columns.Add("ShelfId", typeof(int));

        //    foreach (KeyValuePair<int, int> kvp in liste)
        //    {
        //        DataRow dr = dtCikilanToplar.NewRow();
        //        dr["RollId"] = kvp.Key;
        //        dr["ShelfId"] = kvp.Value;
        //        dtCikilanToplar.Rows.Add(dr);
        //    }

        //    try
        //    {
        //        Main.ceWS.TopYerlestir(dtCikilanToplar);
        //        Terminal.PlaySuccess();

        //        if (var == 0)
        //            this.Close();
        //        btnSave.Enabled = false;
        //    }
        //    catch (Exception ex)
        //    {
        //        ShowException("Veritabanı hatası!", "Hata", ex);
        //    }
        //    SetButtonsStatus(this, true);
        //}


        //private void power_ValueChanged(object sender, EventArgs e)
        //{
        //    Terminal.StopRFID();
        //    Terminal.RFID.SET_PowerControl((uint)power.Value);
        //}



    }
}